package mx.com.switz.autopista.controller;




import mx.com.switz.autopista.dto.Vehiculo;
import mx.com.switz.autopista.exception.AutopistaException;
import mx.com.switz.autopista.service.VehiculoService;
import mx.com.switz.autopista.utils.FileFormBean;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


import org.springframework.ui.ModelMap;

import com.sun.mail.util.BEncoderStream;

@Controller
public class HomeController {

	@Autowired
	VehiculoService vehiculoService; 
	
	@RequestMapping(value = "/agregarVehiculo", method = RequestMethod.GET)
	public String agregar(ModelMap model ,Principal principal, HttpServletRequest request) {
		
		return "vehiculo/agregarVehiculo";
	}
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String inicio(ModelMap model ,Principal principal, HttpServletRequest request) {
		
		return "inicio";
	}
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/inicio", method = RequestMethod.GET)
	public String home(ModelMap model ,Principal principal, HttpServletRequest request) {
		
		final String user = SecurityContextHolder.getContext().getAuthentication().getName();
		HttpSession session = request.getSession(true);
		session.setAttribute("user", user);
		
		//String name = principal.getName();
		//model.addAttribute("username", name);
		//model.addAttribute("message", "Bienvenido");
		return "inicio";
	}
	
	@RequestMapping(value="upload" , method = RequestMethod.GET)
    public @ModelAttribute("fileFormBean") FileFormBean getInitialMessage() {
        return new FileFormBean();
    }
	
	 @RequestMapping(value="upload" , method = RequestMethod.POST)
	    public @ModelAttribute("message") String guardaFichero(@ModelAttribute FileFormBean fileFormBean, HttpServletRequest request) {
	        String dato= "";
	        String ruta = request.getSession().getServletContext().getRealPath("/")+"resources/";
	        try {
	            dato = grabarFicheroALocal(fileFormBean,ruta, "Carros Cuernavaca Morelos");
	        } catch (Exception e) {
	            e.printStackTrace();
	            return "No se ha podido grabar el fichero";
	        }
	         
	        return dato;
	    }
	 
	 
	 @RequestMapping(value="buscar",method=RequestMethod.GET)
		public ModelAndView muestraVehiculos(@RequestParam("begin")int begin,@RequestParam("end")int end,HttpServletRequest request){
			List<Vehiculo> vehiculo=new ArrayList<Vehiculo>();
			
			///(foreach jstl) Vista
			request.setAttribute("inicio",begin);
			request.setAttribute("ultimo",end);
			
			
			
			try {
				//Paginacion
				int division=(int)vehiculoService.selectVehiculoByEstado().size();
				int valor=division/10;
				
				if(valor%10 != 0){
				valor+=1;
				}
				request.setAttribute("division",valor);
				
				vehiculo = vehiculoService.selectVehiculoByEstado();
				return new ModelAndView("buscar","autos",vehiculo);	
			} catch (AutopistaException e) {
				
				e.printStackTrace();
			}
			return new ModelAndView("buscar","autos",vehiculo);	
		}
	
	@RequestMapping(value="json")
	public @ResponseBody Map<String,? extends Object>vehiculo(){
		 
		HashMap<String, List<Vehiculo>> modelMap = new HashMap<String,List<Vehiculo>>();
		 List<Vehiculo> vehiculo=new ArrayList<Vehiculo>();
		 try {
			vehiculo = vehiculoService.selectVehiculoByEstado();
			modelMap.put("datos", vehiculo);
			return modelMap;
		} catch (AutopistaException e) {
			
			return null;
			
		}
		
	 }
	
	@RequestMapping("buscar2")
	public String buscarVehiculo(){
		
		return "buscar";
	}
	 
	 
	 @RequestMapping("contacto")
	 public String contacto(){
		 return "contacto";
	 }
	 
	 @RequestMapping("detalle")
	 public String ofertas(){
		 return "detalle";
	 }
	
	private String grabarFicheroALocal(FileFormBean fileFormBean, String ruta, String nombreEmpresa) throws Exception {
        String ext = "";
        String nombreArchivo = "";
        Random r = new Random();
		String num = r.nextInt(10000)+1+""; 
		File folderEmpresa = new File(ruta + "/" + nombreEmpresa);
        if(!folderEmpresa.exists())
        	folderEmpresa.mkdir();
        String [] palabra = nombreEmpresa.split("\\ ");
		
		
		for (int i = 0 ; i<palabra.length ; i++ ){
			String cadena = palabra[i].substring(0,3);
			nombreArchivo+=cadena;
		}
		
        String path = folderEmpresa.getAbsolutePath();
		CommonsMultipartFile uploaded = fileFormBean.getFichero();
		String name = uploaded.getOriginalFilename();
		
		int i = name.lastIndexOf('.');
		if (i > 0) {
		    ext = name.substring(i+1);
		}
		
        File localFile = new File(path + "/"+ nombreArchivo + num + "." + ext);
        FileOutputStream os = null;
       
        try {
             
            os = new FileOutputStream(localFile);
            os.write(uploaded.getBytes());
            return localFile.getAbsolutePath(); 
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
